#!/bin/bash

# The default delay time is one second.
DELAY_TIME=1

# Create an event log.
create_event_log()
{
    if [ ! -d "/var/log" ]; then
        mkdir -p /var/log
    fi

    if [ $# -lt 2 ]; then
        return 0;
    fi

    OPENBMC_TAG="${1}.0.1.${2}"
    PARA=""
    shift
    while [ $# -ne 0 ]; do
        PARA=$PARA",$1"
        shift
    done
    logger -p local7.info "${OPENBMC_TAG}${PARA}"
}

# Get the value of the dbus attribute.
get_dbus_property()
{
    echo "$(busctl get-property $1 $2 $3 $4 | cut -d " " -f2)"
}

# Set the value of the dbus attribute.
set_dbus_property()
{
    busctl set-property $1 $2 $3 $4 $5 $6
}

# Power status related events.
power_good_event()
{
    if [ $1 -eq 0 ]; then
        # Shutdown reset status.
        if grep -q "aarch64" <<< $(uname -a)
        then
            # Reset vhub controller
            vhub_cfg=$(devmem 0x319c0000)
            devmem 0x319c0000 32 $(($vhub_cfg & ~(0x1 << 12)))
            devmem 0x319c0000 32 $(($vhub_cfg | (0x1 << 12)))
            echo "Reset vhub"

            # Reset DC
            if [ $(($(devmem 0x32001518) & 0x1)) != 0 ]; then
                devmem 0x32001468 32 0x0
                devmem 0x32001a18 32 0x0
                devmem 0x32001518 32 0x18000111
                echo "Reset DC"
            fi
        fi
    fi
}

# Toggle the state of identify LED Group
toggle_identify_led()
{
    service="xyz.openbmc_project.LED.GroupManager"
    path="/xyz/openbmc_project/led/groups/enclosure_identify"
    interface="xyz.openbmc_project.Led.Group"
    property="Asserted"

    value=$(get_dbus_property $service $path $interface $property)
    if $value; then
        set_dbus_property $service $path $interface $property b false
    else
        set_dbus_property $service $path $interface $property b true
    fi
}

print_help()
{
    echo "Usage:"
    echo "    phytium-util <function> [gpioname [gpiovalue]]"

    echo "Command:"
    echo "    powergood|identifyled"

    echo "For example:"
    echo "    phytium-util identifyled"
    echo "    phytium-util powergood         <gpiovalue> [DELAY_TIME=4(defalut 4s)|delaytime]"
}

case "$1" in
    powergood)
	shift

        if [ $2 ]; then
            TIME=$(cut -d '=' -f2 <<< $2)
            RET="^[0-9]+$"
            if [[ $TIME =~ $RET ]]; then
                DELAY_TIME=$TIME
            fi
        else
            DELAY_TIME=4
        fi

	if [ $1 ]; then
            power_good_event $1
	fi
    ;;
    identifyled)
        toggle_identify_led
    ;;
    *)
        print_help
    ;;
esac
